package com.yantong.controller.customer;

import com.yantong.annotation.Log;
import com.yantong.constant.MemberType;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.pojo.BondFlow;
import com.yantong.pojo.*;
import com.yantong.service.MemberPartnerService;
import com.yantong.service.MemberService;
import com.yantong.service.MemberUseragentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
  * @Description:
  * Copyright: Copyright (c) 2018 
  * Company: 会员管理
  * @author xiangyi
  * @version V1.0.0
  * @since 3.0
  * @date 2018年8月28日 下午6:16:38
 */
@Controller
@RequestMapping("/member/manage")
public class MemberController extends BaseController {

    private static final String prefix = "member/manage";
    private static final Logger logger = LoggerFactory.getLogger(MemberController.class);
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberUseragentService memberUseragentService;
    @Autowired
    private MemberPartnerService memberPartnerService;

    /**
     * 会员列表界面
     * @return
     */
    @GetMapping()
    @RequiresPermissions("member:manage:manage")
    public String centres(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        model.addAttribute("startDate", "2019-01-01");
        model.addAttribute("endDate", DateUtils.format(new Date()));
        return prefix + "/members";
    }

    /**
     * 会员列表界面
     * @return
     */
    @GetMapping("agents")
    @RequiresPermissions("member:manage:agents")
    public String agents(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        model.addAttribute("startDate", "2019-01-01");
        model.addAttribute("endDate", DateUtils.format(new Date()));
        return prefix + "/agents";
    }


    /**
     * 会员列表数据 
     * @param listMemberParams
     * @param member
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("member:manage:manage")
    public PageUtils<Member> listMembers(ListMemberParams listMemberParams, Member member, int offset, int limit){
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        return memberService.listMembers(listMemberParams, member, offset, limit);
    }

    /**
     * 合伙人申请列表数据
     */
    @ResponseBody
    @GetMapping("/partnerList")
    @RequiresPermissions("member:manage:partner")
    public PageUtils<MemberPartner> listMemberPartners(ListMemberParams listMemberParams, MemberPartner memberPartner, int offset, int limit){
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        return memberPartnerService.listMemberPartners(listMemberParams, memberPartner, offset, limit);
    }

    /**
	 * 得到门店下面的用户
	 * @param params
	 * @param rowBounds
	 * @return
	 */
    @ResponseBody
    @GetMapping("/getTeamtheUserByMid")
    @RequiresPermissions("commanderList:manage:teamuser")
	public  PageUtils<Member> getTeamtheUserByMid(Long mid,int offset, int limit){
		 return memberService.getTeamtheUserByMid(mid, offset, limit);
	 };

    /**
     * 会员更新
     * @param member
     * @return
     */
    @Log(module = "会员管理", operation = "编辑会员")
    @ResponseBody
    @RequiresPermissions("member:manage:edit")
    @PostMapping("/update")
    public ResultVo update(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }


    @ResponseBody
    @PostMapping("/update2")
    public ResultVo update2(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 供应商调用会员绑定数据
     * @param queryItem 查询关键词，昵称、手机号码、会员姓名
     * @param centreId
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryList")
    public PageUtils<Member> queryList(String queryItem,Long centreId, int offset, int limit, Integer isteam) {
        if (centreId == null) {
            centreId = getUserCentreId();
        }
        return memberService.queryList(queryItem, centreId, offset, limit, isteam);
    }

    /**
     * 查询门店
     */
    @ResponseBody
    @RequestMapping("/queryTeam")
    public PageUtils<Member> queryTeam(String queryItem,Long centreId, int offset, int limit, Integer isteam) {
        if (centreId == null) {
            centreId = getUserCentreId();
        }
        return memberService.queryList(queryItem, centreId, offset, limit, isteam);
    }

    /**
     * 邀请为门店
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:invitation")
    @GetMapping("/invitation/{id}")
    public String invitation(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        return prefix + "/invitation";
    }
    
    /**
     * 邀请为门店
     * @param member
     * @return
     */
    @Log(module = "会员管理", operation = "邀请为门店")
    @ResponseBody
    @RequiresPermissions("member:manage:invitation")
    @PostMapping("/updateInvitation")
    public ResultVo updateInvitation(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        member.setIsteam(MemberType.INVITE_TO_COMMANDER.getCode());
        if(StringUtils.isNotEmpty(member.getLat())){
            String[] str = member.getLat().split(",");
            if(str!=null && str.length>=2){
                member.setLng(str[0]);
                member.setLat(str[1]);
            }else{
                member.setLng(null);
                member.setLat(null);
            }
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    
    /**
     * 黑名单 
     * @param member
     * @return
     */
    @Log(module = "会员管理", operation = "加入黑名单")
    @ResponseBody
    @RequiresPermissions("member:manage:hmd")
    @PostMapping("/hmd")
    public ResultVo hmd(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    

    /**
     * 设为门店
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:setCommander")
    @GetMapping("/setCommander/{id}")
    public String setCommander(@PathVariable Long id, Model model) {
        Member member = memberService.getByKey(id);
        if(StringUtils.isEmpty(member.gettLng()) || StringUtils.isEmpty(member.gettLat())){
            member.setLat("");
        }else{
            member.setLat(member.gettLng() + "," + member.gettLat());
        }
        model.addAttribute("member", member);
        return prefix + "/setCommander";
    }
    
    /**
     * 设为门店-更新
     * @param member
     * @return
     */
    @Log(module = "会员管理", operation = "设为门店")
    @ResponseBody
    @RequiresPermissions("member:manage:setCommander")
    @PostMapping("/setComUpdate")
    public ResultVo setComUpdate(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        member.setsTime(new Date());
        member.setIsteam(MemberType.COMMANDER.getCode());
        //-------↓↓↓↓↓↓↓↓审核通过将自己设置为上次购买门店↓↓↓↓↓↓↓↓↓--------
        String name = "";
        if(!StringUtils.isEmpty(member.getRealname())){
            name = member.getRealname();
        }else{
            if(!StringUtils.isEmpty(member.getNickname())){
                name = member.getNickname();
            }
        }
        member.setUpshopTid(member.getId());
        member.setUpshopName(name);
        member.setTeamid(member.getId());
       //-------↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑--------
        if(StringUtils.isNotEmpty(member.getLat())){
            String[] str = member.getLat().split(",");
            if(str!=null && str.length>=2){
                member.settLng(str[0]);
                member.settLat(str[1]);
            }else{
                member.settLng("");
                member.settLat("");
            }
        }else{
            member.settLng("");
            member.settLat("");
        }
        member.setLat(null);
        if (memberService.updateMemberAndBondFlow(member, null, 0) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    
    /**
     * 选择推荐门店
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:setCommander")
    @GetMapping("/chooseCommander")
    public String chooseCommander(Model model) {
        return prefix +"/chooseCommander";
    }
    
    /**
     * 查询推荐门店
     * @param queryItem
     * @param centreId
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryComList")
    public PageUtils<Member> queryComList(String queryItem,Long centreId, int offset, int limit) {
        if (centreId == null) {
            centreId = getUserCentreId();
        }
        return memberService.queryComList(queryItem, centreId, offset, limit);
    }
    
    /**
     * 会员对应的订单列表 
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("order:manage:manage")
    @GetMapping("/getOrderList/{id}")
    public String getOrderList(@PathVariable String id, Model model) {
        model.addAttribute("id", id);
        return "order/orderToMember";
    }
    
    /**
     * 修改保证金 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/updateBondmoney/{id}")
    public String updateBondmoney(@PathVariable Long id, Model model) {
        Member member = memberService.getByKey(id);
        model.addAttribute("member", member);
        return prefix + "/updateBondmoney";
    }

    /**
     * 修改保证金
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/walletChange/{id}")
    public String walletChange(@PathVariable Long id, Model model) {
        Member member = memberService.getByKey(id);
        model.addAttribute("member", member);
        return prefix + "/walletChange";
    }
    
    /**
     * 更新保证金并插入保证金记录
     * @param member
     * @param bondFlow
     * @return
     */
    @Log(module = "会员管理", operation = "修改保证金")
    @ResponseBody
    @PostMapping("/updateMemberAndBondFlow")
    public ResultVo updateMemberAndBondFlow(Member member, BondFlow bondFlow) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMemberAndBondFlow(member, bondFlow, 1) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 更新保证金并插入保证金记录
     * @param member
     * @param memberWalletLog
     * @return
     */
    @Log(module = "会员管理", operation = "修改保证金")
    @ResponseBody
    @PostMapping("/changeMemberAndWallet")
    public ResultVo changeMemberAndWallet(Member member, MemberWalletLog memberWalletLog) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.changeMemberAndWallet(member, memberWalletLog) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    
    /**
     * 选择赠送门店,多选
     * @param model
     * @return
     */
    @GetMapping("/chooseCheckCommander")
    public String chooseCheckCommander(Model model) {
        return prefix +"/chooseCheckCommander";
    }
    
    
    /**
     * 用户·列表-导出 
     * @param response
     * @param listMemberParams
     * @param member
     */
    @RequiresPermissions("commanderList:manage:export")
    @GetMapping("/exportMembers")
    public void exportMembers(HttpServletResponse response, ListMemberParams listMemberParams, Member member) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"用户ID","用户昵称","余额","总订单数", "注册时间","电话","上次购买门店"};
        resultData.add(0, Arrays.asList(head));
        if(listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        List<Member> list = memberService.epListMembers(listMemberParams, member);
        if (CollectionUtils.isNotEmpty(list)){
            for(Member mem: list) {
                List<Object> row = new ArrayList<>();
                row.add(mem.getId());
                row.add(mem.getNickname());
                row.add(mem.getCredit2());
                row.add("");
                row.add(mem.getCreatetime());
                row.add(mem.getMobile());
                row.add(mem.getUpshopName());
                resultData.add(row);
            }
            String fileName = "用户列表_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
            try {
                ExcelHelper.exportExcel(response, fileName, "用户列表", resultData);
            } catch (IOException e) {
                logger.info("export member error:{}", e.getMessage());
            }
        }
    }
    
    /**
     *    导出门店用户
     */
    @RequiresPermissions("commanderList:manage:exportsTeamUser")
    @GetMapping("/exportsTeamUser")
    public void exportsTeamUser(Long mid, HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"序号", "Id", "用户名","真实姓名", "电话", "地址"};
        resultData.add(0, Arrays.asList(head));
    	List<Member> list = memberService.getTeamtheUserByMid(mid);
        if (CollectionUtils.isNotEmpty(list)) {
        	int indexer = 1;
            for (Member o: list) {
                if (o == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(indexer);
                row.add(o.getId());
                row.add(o.getNickname());
                row.add(o.getRealname());
                row.add(o.getMobile());
                row.add(o.getAddress());
                indexer++;
                resultData.add(row);
            }
        }
        String fileName = "门店用户_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "门店用户", resultData);
        } catch (IOException e) {
            logger.info("export order list error:{}", e.getMessage());
        }
    }

    /**
     * 店员列表界面
     * @return
     */
    @GetMapping("clerk")
    @RequiresPermissions("member:manage:clerk")
    public String clerk(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        model.addAttribute("startDate", DateUtils.format(DateUtils.getAddDayDate(new Date(), -7)));
        model.addAttribute("endDate", DateUtils.format(new Date()));
        return prefix + "/clerk";
    }


    /**
     * 编辑店员
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:editClerk")
    @GetMapping("/editClerk/{id}")
    public String editClerk(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        model.addAllAttributes(getTeamIdModelInfo());
        return prefix + "/editClerk";
    }

    /**
     * 编辑会员
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        return prefix + "/edit";
    }


    /**
     * 设置店员密码
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:editClerk")
    @GetMapping("/setPassword/{id}")
    public String setPassword(@PathVariable Long id, Model model) {
        model.addAttribute("id", id);
        return prefix + "/setPassword";
    }


    /**
     * 设置店员折扣
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("member:manage:editClerk")
    @GetMapping("/setDiscount/{id}")
    public String setDiscount(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        return prefix + "/setDiscount";
    }

    /**
     * 合伙人申请列表界面
     */
    @GetMapping("partner")
    @RequiresPermissions("member:manage:partner")
    public String partner() {
        return prefix + "/memberPartner";
    }

    /**
     * 会员更新
     * @param member
     * @return
     */
    @Log(module = "会员管理", operation = "编辑会员")
    @ResponseBody
    @RequiresPermissions("member:manage:edit")
    @PostMapping("/updatePasswrod")
    public ResultVo updatePassword(UpdatePasswordReq updatePasswordReq) {
        if (updatePasswordReq == null || updatePasswordReq.getId() == null || StringUtils.isEmpty(updatePasswordReq.getPassword())) {
            return ResultVo.error();
        }
        if (updatePasswordReq == null || updatePasswordReq.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updatePassword(updatePasswordReq) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 更新会员状态并发放佣金
     * @param mid
     * @return
     */
    @Log(module = "会员管理", operation = "修改会员状态并发放佣金")
    @ResponseBody
    @PostMapping("/updateMeberVipAndCommission")
    public ResultVo updateMeberVipAndCommission(Long mid) {
        if (mid == null) {
            return ResultVo.error();
        }
        if (memberService.updateMeberVipAndCommission(mid) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }


}
